<template>
  <ContentWrap>
    <view class="tableOp">
      <el-row type="flex" justify="end">
        <el-button style="" type="primary" @click="showAdd">
          <Icon class="mr-5px" icon="ep:plus" />{{ $t(`global.record`) }}
        </el-button>
      </el-row>
    </view>

    <el-row>
      <el-col :span="24">
        <el-table v-loading="loading" :data="list" :border="true" @row-click="tagPrintDetails">
          <el-table-column type="index" />
          <el-table-column v-for="(item, index) in checkCol" :key="index" :prop="item.prop" :label="item.label"
            :width="item.width">
            <template #default="scope">
              <view v-if="item.label === '打印样式'">
                <dict-tag :type="DICT_TYPE.HKB_PRINT_STYLE" :value="scope.row.printstyle" />
              </view>
              <view v-if="item.label === '打印尺寸'">
                <dict-tag :type="DICT_TYPE.HKB_PRINT_SIZE" :value="scope.row.printsize" />
              </view>
              <view v-if="item.label === '商品管理'">
                <view class="flex flex-wrap">
                  <el-tag v-for="item1 in scope.row.list" :key="item1" class="tag">
                    {{ item1.number }}
                  </el-tag>
                </view>
              </view>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <span @click.stop>
                  <el-button link type="primary" @click="editDetails(scope.row)">
                    <Icon class="mr-5px" icon="ep:edit" />
                  </el-button>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total"
      @pagination="getList" />

    <el-dialog v-model="showTagDetail" @closed="cacel" width="80vw">
      <template #header>
        <el-row type="flex" justify="end">
          <el-button v-if="isEdit" type="danger" @click="deleteTagPrint">
            <Icon class="mr-5px" icon="ep:delete" />删除
          </el-button>
        </el-row>
      </template>
      <el-form id="pdfDom" :model="tagInfo" ref="tagPrintFormRef" label-position="top">
        <el-tag type="info" style="margin-bottom: 10px">标签打印</el-tag>
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item prop="id" label="打印批次">
              <el-text style="font-size: 24px; font-weight: 500">{{ tagInfo.id }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="打印样式">
              <el-select v-model="tagInfo.printstyle" clearable style="width: 100%" :disabled="!isEdit && !isAdd">
                <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HKB_PRINT_STYLE)" :key="dict.value"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="打印尺寸">
              <el-select v-model="tagInfo.printsize" clearable style="width: 100%" :disabled="!isEdit && !isAdd">
                <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HKB_PRINT_SIZE)" :key="dict.value"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注说明">
          <span v-if="!isEdit && !isAdd">{{ tagInfo.memo }}</span>
          <el-input v-model="tagInfo.memo" v-else />
        </el-form-item>
        <el-form-item label="商品管理">
          <proList v-model="tagInfo.list" :readonly="!isAdd && !isEdit" />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-button type="primary" v-if="isEdit || isAdd" @click="submitForm">{{ $t(`global.verify`) }}</el-button>
        <el-button type="primary" v-if="!isEdit && !isAdd" v-print="printObj" @click="printPro">打印</el-button>
        <el-button @click="cacel">{{$t(`global.cancel`)}}</el-button>
      </el-row>
    </el-dialog>

    <view id="printTable" v-show="isPrint">
      <view v-for="(item, index) in tagInfo.list" :key="index" style="display:flex; flex-direction: row">
        <el-text>商品名称：{{item.goods}}</el-text>
        <el-image :preview-src-list="['data:image/jpeg;base64,' + item.qrcode]"
                  :src="'data:image/jpeg;base64,' + item.qrcode" style="width: 200px; height: 200px"
                  :z-index="10" />
      </view>
    </view>

  </ContentWrap>
</template>
<script lang="ts" setup>
import { FormInstance } from 'element-plus'
import * as tagPrintApi from '@/service/api/hkb/tagPrint/index'
import proList from '@/pages/hkb/components/proList/index.vue'
import { ref } from 'vue'
import type { TagPrintVO, ColumnVO, goodsVO } from '../types'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'


const message = useMessage() // 消息弹窗

// defineOptions({ name: 'TagPrint' })

const showTagDetail = ref(false)
const isAdd = ref(false) //是否新增
const isEdit = ref(false) //是否编辑
const loading = ref(false) // 列表的加载中
const buttonLoading = ref(false) //按钮的加载
const total = ref(0) // 列表的总页数
// 列表的数据
const list = ref<TagPrintVO[]>([])
const fileDetailList = ref([])
const accessDetail = ref(false)
const isPrint = ref(false)

const printObj = {
  id: 'printTable',
  // preview:true, // 打印预览
  // previewTitle: '打印预览',
  popTitle: '商品二维码',
  extraCss: "https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css",
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
  beforeOpenCallback (vue) {
    console.log('打开之前')
    console.log(isPrint.value)
  },
  openCallback (vue) {
    console.log('执行了打印')
  },
  closeCallback (vue) {
    console.log('关闭了打印工具')
    isPrint.value = false
  }
}

//商品字段
const allCol = ref([
  { label: '打印批次', prop: 'id', width: '' },
  { label: '打印样式', prop: 'printstyle', width: '' },
  { label: '打印尺寸', prop: 'printsize', width: '' },
  { label: '备注说明', prop: 'memo', width: '' },
  { label: '商品管理', prop: 'list', width: '' }
])

const checkCol = ref<ColumnVO[]>([])
const checked = ref([])

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})

const tagPrintFormRef = ref<FormInstance>()
const tagInfo = ref({
  id: '',
  printstyle: '',
  printsize: '',
  memo: '',
  productids: '',
  list: []
})
const tagInfoInitForm = ref({
  id: '',
  printstyle: '',
  printsize: '',
  memo: '',
  productids: '',
  list: []
})

const getList = async () => {
  const res = await tagPrintApi.getList(queryParams.value)
  console.log(res)
  if (res.list.length > 0) {
    list.value = res.list
    total.value = res.total
  }
}


//提交
const submitForm = async () => {
  tagInfo.value.productids = tagInfo.value.list.map((item: goodsVO) => item.id).join(';')
  tagPrintFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true
      if (tagInfo.value.id) {
        await tagPrintApi.editPrint(tagInfo.value).finally(() => (buttonLoading.value = false))
      } else {
        await tagPrintApi.addPrint(tagInfo.value).finally(() => (buttonLoading.value = false))
      }
      showTagDetail.value = false
      await getList()
    }
  })
}

//删除打印
const deleteTagPrint = async () => {
  try {
    // 二次确认
    await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
    // 提交执行
    tagPrintApi.deletePrint(tagInfo.value.id).then((res) => {
      if (res) {
        message.success('删除成功')
      } else {
        message.warning('删除失败')
      }
    }).finally(() => (cacel(), getList()))
  } catch (error) { }
}


//详情
const tagPrintDetails = (row: TagPrintVO) => {
  isAdd.value = false
  isEdit.value = false
  showTagDetail.value = true
  tagInfo.value = JSON.parse(JSON.stringify(row))
}

/** 编辑详情 **/
const editDetails = (row) => {
  isEdit.value = true
  isAdd.value = false
  showTagDetail.value = true
  tagInfo.value = JSON.parse(JSON.stringify(row))
}

//显示新增
const showAdd = async () => {
  isAdd.value = true
  isEdit.value = false
  showTagDetail.value = true
  tagInfo.value = JSON.parse(JSON.stringify(tagInfoInitForm.value))
}

//关闭弹窗
const cacel = () => {
  showTagDetail.value = false
  accessDetail.value = false
  tagPrintFormRef.value?.resetFields()
  fileDetailList.value = []
}

/** 打印 **/
const printPro = () => {
  isPrint.value = true
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  await getList()
  checkCol.value = JSON.parse(JSON.stringify(allCol.value))
  checked.value = JSON.parse(JSON.stringify(allCol.value.map((item) => item.label)))
})
</script>
<style lang="scss" scoped>
.tableOp {
  margin-bottom: 10px;
}

.tag {
  margin: 5px 5px;
}
</style>
